var express = require('express');
var router = express.Router();
var fs = require('fs');
var {resolve} = require('path');
var session = require('express-session');

router.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: ('name','value',{
    maxAge: 60000,
    secure: false
  })
}));

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//检验是否已经登录，如果没有登录，则转到登录页面
router.get('/checklogin',(req,res)=>{
  /*
  let cookie = req.cookies.userName;
  if(!cookie){
    res.send('alers("请登录以后再操作！");location.href="./login.html"');
  }else{
    res.send('0');
  }
  */

  let userInfo = req.session.userInfo;
  if(!userInfo){
    res.send('alers("请登录以后再操作！");location.href="./login.html"');
  }else{
    res.send('window.userInfo = "' + userInfo + '";');
  }

});

router.post('/login',(req,res)=>{
  let user = req.body.username;
  let pass = req.body.password;

  let fusers = resolve(__dirname,'../public/data/user.json');
  let users  = JSON.parse(fs.readFileSync(fusers).toString('utf-8'));

for(var i=0; i<users.length;i++){
  if(users[i].username === user && users[i].password === password){
    /*
    res.cookie('userName',user,{
      maxAge: 20000,
      httpOnly:true
    });
    */
   req.session.userInfo=user;
    res.send({
      code: 0,
      msg: 'ok'
    });
    break;
  }
}
if(i===users.length){
  res.send({
    code:1,
    msg:'error'
  });
}

  res.end();
});

module.exports = router;
